import 'dart:collection';

import 'package:aio/aio.dart';
import 'package:app/src/utils/unit_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/order_item_info.dart';
import 'package:app/src/http/bean/wroks/product_bean.dart';
import 'package:app/src/http/bean/wroks/special_clauses.dart';
import 'package:app/src/http/model/material_requisition_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/a_combined_utils.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../../../http/bean/clockin/attendances.dart';
import '../../../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../../../http/bean/wroks/carfreightrates_bean.dart';
import '../../../../../../http/bean/wroks/dispatchingaudit_bean.dart';
import '../../../../../../http/bean/wroks/workreview_bean.dart';
import '../../../../../../http/model/ajaxsales_model.dart';
import '../../../../../../http/model/config_model.dart';
import '../../../../../app_ui.dart';

///物料请购
class UiMaterialForm {
  static String _SupplierId = ""; //供应商id
  static bool isModifyBeizhu = false; //备注是否可以修改
  static Widget build(
      BuildContext context, MaterialInfo? materialInfo, bool isBeizhu,
      {String? title}) {
    _SupplierId = materialInfo?.SupplierId ?? "";
    isModifyBeizhu = isBeizhu;
    return StatefulBuilder(builder: (context, setState) {
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).MaterialInfo; //物料信息
      }
      children.add(UiBase.title(context, title,
          bottom: AppEdgeInsets.margin_bottom)); //标题
      children.add(_table(context, materialInfo!));
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _setState = null;

  static Widget _table(BuildContext context, MaterialInfo materialInfo) {
    if (materialInfo?.PurDemandList == null ||
        materialInfo!.PurDemandList!.length <= 0) {
      return LibUi.getEmptyView();
    }
    //fixme 表格
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      //可以水平滑动的表格
      var scrolltable = _scrolltable(context, materialInfo);
      //水平滑动效果
      var singleChildScrollView = SingleChildScrollView(
          child: scrolltable, scrollDirection: Axis.horizontal);
      return Center(
        child: Container(
          child: singleChildScrollView,
          //width: 2400,
        ),
      );
    });
  }

  static Map<String, TextSelection?> _mtextSelectionMap = HashMap();

  static TextSelection? getTextSelection(String key) {
    return _mtextSelectionMap[key];
  }

  static void setTextSelection(String key, TextSelection? textSelection) {
    _mtextSelectionMap[key] = textSelection;
  }

  static void clearTextSelection() {
    _mtextSelectionMap?.clear();
  }

  ///水平滑动表格
  static Widget _scrolltable(BuildContext context, MaterialInfo materialInfo) {
    if (materialInfo.PurDemandList == null ||
        materialInfo.PurDemandList!.length <= 0) {
      return AppUi.getEmptyView();
    }
    List<PurDemand> datas = materialInfo.PurDemandList!;
    var firstData = datas[0];
    var isAdd = materialInfo.isCanoOeration(); //是否可以添加(是否可操作)
    var children = <TableRow>[];
    //第一行标题栏
    List<Widget> titleChildren = [];
    if (isAdd) {
      titleChildren.add(_text("")); //加号
    }
    titleChildren.add(_text(AppStrings.of(context).TheSerial)); //序号
    titleChildren.add(_text(AppStrings.of(context).MaterialName3)); //物料名称
    titleChildren.add(_text(AppStrings.of(context).TypeOfMaterial)); //物料类型
    titleChildren.add(_text(AppStrings.of(context).MaterialCode)); //物料编码
    titleChildren.add(_text(AppStrings.of(context).Width_Height)); //规格型号
    if (firstData.Iswidth2()) {
      titleChildren.add(_text(AppStrings.of(context).ItemWidth)); //宽
    }
    if (firstData.Isheight2()) {
      titleChildren.add(_text(AppStrings.of(context).ItemHeight)); //高
    }
    if (firstData.Islength2()) {
      titleChildren.add(_text(AppStrings.of(context).long)); //长
    }
    if (firstData.Isthickness2()) {
      titleChildren.add(_text(AppStrings.of(context).thickness2)); //厚
    }
    if (firstData.Isquantity2()) {
      titleChildren.add(_text(AppStrings.of(context).ItemNum)); //数量
    }
    if (!firstData.isMT01()) {
      //辅料，五金；显示；包数量，和每包数量。
      titleChildren
          .add(_text(AppStrings.of(context).PackageCount, isStart: true)); //包数量
      titleChildren.add(
          _text(AppStrings.of(context).PackageListCount, isStart: true)); //每包数量
    }
    titleChildren.add(_text(AppStrings.of(context).NumberOfApplications,
        isStart: true)); //申请数量*
    if (firstData.isSubsidiaryNum()) {
      titleChildren.add(_text(AppStrings.of(context).Area)); //面积
    }
    titleChildren.add(_text(AppStrings.of(context).ManufacturerName)); //品牌
    titleChildren.add(_text(AppStrings.of(context).CurrentInventory)); //当前库存
    titleChildren.add(_text(AppStrings.of(context).Note)); //备注
    if (isAdd) {
      titleChildren.add(_text(AppStrings.of(context).Operation)); //操作
    }
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: titleChildren);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      List<Widget> rowChildren = [];
      //加号
      if (isAdd) {
        rowChildren.add(Row(
          children: [
            InkWell(
              child: Icon(
                Icons.add,
                color: Colors.blueAccent,
                size: 33,
              ),
              onTap: () {
                _setState?.call(() {
                  //复制
                  datas?.add(datas[i].copy());
                });
              },
            ),
          ],
        ));
      }
      //序号
      var TheSerial = _text("${i + 1}");
      rowChildren.add(TheSerial);
      //物料名称
      var MaterialName = _text("${data.MaterialName}");
      rowChildren.add(MaterialName);
      //物料类型
      var MaterialType = _text("${data.getMaterialTypeName(context)}");
      rowChildren.add(MaterialType);

      StateSetter? MaterialCodeSetState = null; //物料编码
      StateSetter? CurrentInventorySetState = null; //库存数量
      ///物料编码
      var MaterialCodeW = StatefulBuilder(
        builder: (contxet, setState) {
          MaterialCodeSetState = setState;
          if (data.isFirstMaterialCode) {
            getMaterialNumber(_SupplierId, context, MaterialCodeSetState,
                data); //fixme 通过规则获取物料编码
            data.isFirstMaterialCode = false; //fixme 标志不是首次加载。
          }
          var MaterialCode = _text("${data.MaterialCode}");
          return MaterialCode;
        },
      );
      rowChildren.add(MaterialCodeW);
      StateSetter? sizeSetState = null; //规格
      if (firstData.isOperationSize()) {
        //规格型号,可手动填写。
        var Width_Height = StatefulBuilder(
          builder: (contxet, setState) {
            sizeSetState = setState;
            return UiBase.itemWithSigleEdit(context, data?.Size,
                isAllowEmpty: true, isLine: true, onChanged: (value) {
              data?.Size = value;
              getStockNum(context, CurrentInventorySetState,
                  MaterialCodeSetState, data);

              ///库存数量
            });
          },
        );
        rowChildren.add(Width_Height);
      } else {
        //规格，不可填写
        var Width_Height = StatefulBuilder(
          builder: (contxet, setState) {
            sizeSetState = setState;
            if (firstData.isMT01()) {
              data?.Size = "${data?.Width}*${data?.Height}";
            }
            return _text(data?.Size);
          },
        );
        rowChildren.add(Width_Height);
      }

      StateSetter? NumberOfApplications = null; //申请数量
      var isDemandNumUpdate = false; //是否实时修改申请数量
      StateSetter? SubsidiaryNumSetState = null; //辅助数量（原片里面是面积）
      StateSetter? PackageCountSetState = null; //包数量
      StateSetter? PackageListCountSetState = null; //每包数量
      if (firstData.Iswidth2()) {
        //宽
        if (firstData.Iswidth) {
          //原片
          TextEditingController? _controller;
          var _key = "Width:${data?.ListId}${data?.index}_${i}";
          var _w = data?.getWidthInput();
          if (firstData.isMT01()) {
            _w = data?.Width; //原片，宽和高会参与规格显示；所以保持原始数据。
          }
          var Width = UiBase.itemWithSigleEdit(context, _w,
              unit: data?.WidthUnit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    // if (data?.WidthInput == "0") {
                    //   data?.WidthInput ="";
                    //   _controller?.value = TextEditingValue(text: "");
                    // }
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    // _controller?.value =
                    //     TextEditingValue(text: "${data?.WidthInput}");
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.Width = "0"; //不能为空，为空，提交接口会报数据格式错误。
                  data?.WidthInput = "0";
                } else {
                  //data?.Width = value;
                  data?.WidthInput = value;
                  data?.Width =
                      AppUnitUtils.unittomm(data?.WidthUnit, value).toString();
                }
                sizeSetState?.call(() {}); //规格更新
                isDemandNumUpdate = true;
                NumberOfApplications?.call(() {
                  data?.autoDemandNum(isDemandNumUpdate, isPackageCount: true);
                  PackageCountSetState?.call(() {});
                  PackageListCountSetState?.call(() {});
                }); //申请数量
                SubsidiaryNumSetState?.call(() {}); //原片辅助数量(面积)
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          rowChildren.add(Width);
        } else {
          var _w = data?.getWidthInput();
          if (firstData.isMT01()) {
            _w = data?.Width; //原片，宽和高会参与规格显示；所以保持原始数据。
          }
          var ItemWidth = _text("${_w}${data?.WidthUnit}");
          rowChildren.add(ItemWidth);
        }
      }
      if (firstData.Isheight2()) {
        //高
        if (firstData.Isheight) {
          //原片
          TextEditingController? _controller;
          var _key = "Height:${data?.ListId}${data?.index}_${i}";
          var _h = data?.getHeightInput();
          if (firstData.isMT01()) {
            _h = data?.Height; //原片，宽和高会参与规格显示；所以保持原始数据。
          }
          var Height = UiBase.itemWithSigleEdit(context, _h,
              unit: data?.HeightUnit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.Height = "0"; //不能为空，为空，提交接口会报数据格式错误。
                  data?.HeightInput = "0";
                } else {
                  //data?.Height = value;
                  data?.HeightInput = value;
                  data?.Height =
                      AppUnitUtils.unittomm(data?.HeightUnit, value).toString();
                }
                sizeSetState?.call(() {}); //规格更新
                isDemandNumUpdate = true;
                NumberOfApplications?.call(() {
                  data?.autoDemandNum(isDemandNumUpdate, isPackageCount: true);
                  PackageCountSetState?.call(() {});
                  PackageListCountSetState?.call(() {});
                }); //申请数量
                SubsidiaryNumSetState?.call(() {}); //原片辅助数量(面积)
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          rowChildren.add(Height);
        } else {
          var _h = data?.getHeightInput();
          if (firstData.isMT01()) {
            _h = data?.Height; //原片，宽和高会参与规格显示；所以保持原始数据。
          }
          var ItemHeight = _text("${_h}${data?.HeightUnit}");
          rowChildren.add(ItemHeight);
        }
      }
      if (firstData.Islength2()) {
        if (firstData.Islength) {
          //长
          TextEditingController? _controller;
          var _key = "Lengths:${data?.ListId}${data?.index}_${i}";
          var Lengths = UiBase.itemWithSigleEdit(
              context, data?.getLengthsInput(),
              unit: data?.LengthUnit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.Lengths = "0"; //不能为空，为空，提交接口会报数据格式错误。
                  data?.LengthsInput = "0";
                } else {
                  //data?.Lengths = value;
                  data?.LengthsInput = value;
                  data?.Lengths =
                      AppUnitUtils.unittomm(data?.LengthUnit, value).toString();
                }
                isDemandNumUpdate = true;
                NumberOfApplications?.call(() {
                  data?.autoDemandNum(isDemandNumUpdate, isPackageCount: true);
                  PackageCountSetState?.call(() {});
                  PackageListCountSetState?.call(() {});
                }); //申请数量
                ///sizeSetState?.call(() {}); //规格更新
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          rowChildren.add(Lengths);
        } else {
          var long = _text("${data?.getLengthsInput()}${data?.LengthUnit}");
          rowChildren.add(long);
        }
      }
      if (firstData.Isthickness2()) {
        if (firstData.Isthickness && !firstData.isMT02()) {
          //厚;(辅料的厚度不允许修改。)
          TextEditingController? _controller;
          var _key = "Thickness:${data?.ListId}${data?.index}_${i}";
          var Thickness =
              UiBase.itemWithSigleEdit(context, data?.getThicknessInput(),
                  unit: data?.ThicknessUnit,
                  onController: (value) {
                    _controller = value;
                  },
                  mtextSelection: getTextSelection(_key),
                  focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                    (value) {
                      if (value) {
                        //聚焦
                        setTextSelection(_key, _controller?.selection); //记录焦点位置
                      } else {
                        //失去焦点
                        setTextSelection(_key, null);
                      }
                    },
                  ),
                  isAllowEmpty: true,
                  isDecimal: true,
                  isNegative: false,
                  isLine: true,
                  onChanged: (value) {
                    if (StringUtils.isEmpty(value)) {
                      data?.Thickness = "0"; //不能为空，为空，提交接口会报数据格式错误。
                      data?.ThicknessInput = "0";
                    } else {
                      //data?.Thickness = value;
                      data?.ThicknessInput = value;
                      data?.Thickness =
                          AppUnitUtils.unittomm(data?.ThicknessUnit, value)
                              .toString();
                    }
                    isDemandNumUpdate = true;
                    NumberOfApplications?.call(() {
                      data?.autoDemandNum(isDemandNumUpdate,
                          isPackageCount: true);
                      PackageCountSetState?.call(() {});
                      PackageListCountSetState?.call(() {});
                    }); //申请数量
                    ///sizeSetState?.call(() {}); //规格更新
                    getStockNum(context, CurrentInventorySetState,
                        MaterialCodeSetState, data);

                    ///库存数量
                  });
          rowChildren.add(Thickness);
        } else {
          //厚
          var thickness =
              _text("${data?.getThicknessInput()}${data?.ThicknessUnit}");
          rowChildren.add(thickness);
        }
      }
      if (firstData.Isquantity2()) {
        if (firstData.Isquantity) {
          //数量
          TextEditingController? _controller;
          var _key = "Numbers:${data?.ListId}${data?.index}_${i}";
          var Numbers = UiBase.itemWithSigleEdit(
              context,
              AppUnitUtils.getStringAs0(
                  StringUtils.toStringAsDecimal(data?.Numbers)),
              unit: data?.QuantityUnit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.Numbers = "0"; //不能为空，为空，提交接口会报数据格式错误。
                } else {
                  data?.Numbers = value;
                }
                isDemandNumUpdate = true;
                NumberOfApplications?.call(() {
                  data?.autoDemandNum(isDemandNumUpdate, isPackageCount: true);
                  PackageCountSetState?.call(() {});
                  PackageListCountSetState?.call(() {});
                }); //申请数量
                ///sizeSetState?.call(() {}); //规格更新
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          rowChildren.add(Numbers);
        } else {
          //数量
          // var ItemNum = _text(AppUnitUtils.getStringAs0(data?.Numbers),);
          var ItemNum = _text(data?.getNumbersStrAndUnit());
          rowChildren.add(ItemNum);
        }
      }
      if (!firstData.isMT01()) {
        //fixme 辅料，五金；显示；包数量，和每包数量。
        //包数量
        var PackageCount = StatefulBuilder(builder: (contxet, setState) {
          PackageCountSetState = setState;
          TextEditingController? _controller;
          var _key = "PackageCount:${data?.ListId}${data?.index}_${i}";
          var PackageCount = UiBase.itemWithSigleEdit(
              context, StringUtils.toStringAsDecimal(data?.PackageCount),
              unit: data?.PackageUnit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.PackageCount = "0"; //不能为空，为空，提交接口会报数据格式错误。
                } else {
                  data?.PackageCount = value;
                }
                isDemandNumUpdate = false;
                if (data.isEmptyPackageCount() ||
                    data.isEmptyPackageListCount()) {
                  data?.DemandNum = "0";
                  data?.MinNum = data?.DemandNum;
                } else {
                  data?.DemandNum = DecimalUtils.multiply(
                      data?.toDouble(data?.PackageCount).toString(),
                      data
                          ?.toDouble(data?.PackageListCount)
                          .toString()); //fixme 申请数量就等于包数量*每包数量
                  data?.MinNum = data?.DemandNum;
                }

                NumberOfApplications?.call(() {}); //申请数量
                ///sizeSetState?.call(() {}); //规格更新
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          return PackageCount;
        });
        rowChildren.add(PackageCount);

        //每包数量
        var PackageListCount = StatefulBuilder(builder: (contxet, setState) {
          PackageListCountSetState = setState;
          TextEditingController? _controller;
          var _key = "PackageListCount:${data?.ListId}${data?.index}_${i}";
          var _unit = "${data?.MainUnit}/${data?.PackageUnit}";
          var PackageListCount = UiBase.itemWithSigleEdit(
              context, StringUtils.toStringAsDecimal(data?.PackageListCount),
              unit: _unit,
              onController: (value) {
                _controller = value;
              },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ),
              isAllowEmpty: true,
              isDecimal: true,
              isNegative: false,
              isLine: true,
              onChanged: (value) {
                if (StringUtils.isEmpty(value)) {
                  data?.PackageListCount = "0"; //不能为空，为空，提交接口会报数据格式错误。
                } else {
                  data?.PackageListCount = value;
                }
                isDemandNumUpdate = false;
                if (data.isEmptyPackageCount() ||
                    data.isEmptyPackageListCount()) {
                  data?.DemandNum = "0";
                  data?.MinNum = data?.DemandNum;
                } else {
                  data?.DemandNum = DecimalUtils.multiply(
                      data?.toDouble(data?.PackageCount).toString(),
                      data
                          ?.toDouble(data?.PackageListCount)
                          .toString()); //fixme 申请数量就等于包数量*每包数量
                  data?.MinNum = data?.DemandNum;
                }
                NumberOfApplications?.call(() {}); //申请数量
                ///sizeSetState?.call(() {}); //规格更新
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              });
          return PackageListCount;
        });
        rowChildren.add(PackageListCount);
      }
      //申请数量
      // data?.MinNum = data
      //     ?.DemandNum; //fixme 防止 MinNum与DemandNum不同；物料请购提交服务器使用的申请数量是MinNum这个字段；（请购申请，物料请购时，注意。）
      var NumberOfApplications2 = StatefulBuilder(
        builder: (contxet, setState) {
          NumberOfApplications = setState;
          // if (data != null && !data!.isMT01() && isDemandNumUpdate) {
          //   ///fixme 非原片类型；申请数量可以手动计算
          //   int count = 0;
          //   if (data.Iswidth) {
          //     count++;
          //   }
          //   if (data.Isheight) {
          //     count++;
          //   }
          //   if (data.Islength) {
          //     count++;
          //   }
          //   if (data.Isthickness) {
          //     count++;
          //   }
          //   if (count > 0) {
          //     try {
          //       //fixme 旧的计算。
          //       // double n = 1000;
          //       // if (count == 1) {
          //       //   n = 1000;
          //       // } else if (count == 2) {
          //       //   n = 1000000;
          //       // } else if (count == 3 || count == 4) {
          //       //   n = 1000000000;
          //       // }
          //       // var applyNum = ((((data.Width2() *
          //       //             data.Height2() *
          //       //             data.Lengths2() *
          //       //             data.Thickness2()) /
          //       //         n) *
          //       //     data.Numbers2())); //长宽高
          //       // print(
          //       //     "count:${count}\tWidth2:${data.Width2()}\tHeight2:${data.Height2()}\tLengths2:${data.Lengths2()}\tThickness2:${data.Thickness2()}\tn:${n}\tNumbers2:${data.Numbers2()}\tapplyNum:$applyNum");
          //
          //       ///fixme 新的计算方式
          //       double? _width = data.Width2().toDouble(); //宽
          //       double? _height = data.Height2().toDouble(); //高
          //       double? _lengths = data.Lengths2().toDouble(); //长
          //       double? _thickness = data.Thickness2().toDouble(); //厚
          //       double? _numbers = data.Numbers2().toDouble(); //数量
          //       double baseUnit = 1000; //1米等于1000毫米。
          //       if (data.Iswidth) {
          //         //宽
          //         var unit = baseUnit;
          //         _width = DecimalUtils.divide(_width, unit);
          //         if (_width == null || _width <= 0) {
          //           _width = 1; //fixme 小于等于0都当1处理
          //         }
          //       } else {
          //         _width = 1; //fixme 不可填写，就当1处理，不用参与计算
          //       }
          //       if (data.Isheight) {
          //         //高
          //         var unit = baseUnit;
          //         _height = DecimalUtils.divide(_height, unit);
          //         if (_height == null || _height <= 0) {
          //           _height = 1; //fixme 小于等于0都当1处理
          //         }
          //       } else {
          //         _height = 1;
          //       }
          //       if (data.Islength) {
          //         //长
          //         var unit = baseUnit;
          //         _lengths = DecimalUtils.divide(_lengths, unit);
          //         if (_lengths == null || _lengths <= 0) {
          //           _lengths = 1; //fixme 小于等于0都当1处理
          //         }
          //       } else {
          //         _lengths = 1;
          //       }
          //       if (data.Isthickness && !firstData.isMT02()) {
          //         //厚；辅料的厚度不允许修改
          //         var unit = baseUnit;
          //         _thickness = DecimalUtils.divide(_thickness, unit);
          //         if (_thickness == null || _thickness <= 0) {
          //           _thickness = 1; //fixme 小于等于0都当1处理
          //         }
          //       } else {
          //         _thickness = 1;
          //       }
          //       if (data.Isquantity) {
          //         if (_numbers <= 0) {
          //           _numbers = 1; //fixme 数量少于0，就当1计算。
          //         }
          //       } else {
          //         _numbers = 1;
          //       }
          //       //fixme 乘法：宽*高*长*厚度
          //       var num1 = DecimalUtils.multiply(_width, _height);
          //       // print("_width:$_width\t_height:$_height\tnum1:$num1");
          //       var num2 = DecimalUtils.multiply(_lengths, _thickness);
          //       // print("_lengths:$_lengths\_thickness:$_thickness\tnum2:$num2");
          //       var num3 = DecimalUtils.multiply(num1, num2);
          //       // print("num1:$num1\tnum2:$num2\tnum3:$num3");
          //       //fixme 除法：除以转化单位
          //       // print("num3:$num3\tn:$n");
          //       //var num4 = DecimalUtils.divide(num3, n.toDouble());//fixme 上面已经分别除过了，就不需要再统一除了。
          //       // print("num3:$num3\tn:$n\tnum4:$num4");
          //       //fixme 乘法：乘以数量
          //       // double? num5 = DecimalUtils.multiply(num4, _numbers);
          //       double? num5 = DecimalUtils.multiply(num3, _numbers);
          //       // print("num5:$num5");
          //       double applyNum = num5 ?? 0;
          //
          //       if (applyNum <= 0) {
          //         data?.DemandNum = "0";
          //         data?.MinNum = "0";
          //       } else {
          //         //var s = applyNum.toString();
          //         var s = NumUtil.parse(applyNum);
          //         if (s.contains(".")) {
          //           //var applyNum2 = applyNum.toStringAsFixed(4);
          //           var applyNum2 = s; //直接显示完整的文本；不截取小数了。
          //           //print("申请数量手动计算：$applyNum\t$applyNum2");
          //           data?.DemandNum = applyNum2;
          //           data?.MinNum = applyNum2;
          //         } else {
          //           data?.DemandNum = s;
          //           data?.MinNum = s;
          //         }
          //       }
          //     } catch (e) {
          //       print("申请数量计算异常：$e");
          //     }
          //   }
          // }
          // if (isDemandNumUpdate) {
          //   data?.PackageCount = "1"; //包数量，自己赋值为1。
          //   data?.PackageListCount = data?.DemandNum; //每包数量，就赋值为申请数量。
          //   // PackageCountSetState?.call(() {}); //包数量
          //   // PackageListCountSetState?.call(() {}); //每包数量
          //   isDemandNumUpdate = false;
          // }
          var _readOnly = false;
          if (!firstData.isMT01()) {
            _readOnly = true; //辅料，五金，直接填包数量和每包数量。申请数量暂时不输入和pc保持一致。
          }
          TextEditingController? _controller;
          var _key = "key:${data?.ListId}${data?.index}_${i}";
          var _edit = UiBase.itemWithSigleEdit(
              context, AppUnitUtils.getStringAs0(data?.DemandNum),
              isAllowEmpty: true,
              isDecimal: true,
              readOnly: _readOnly,
              unit: data?.MainUnit ?? "",
              isNegative: false, onChanged: (value) {
            data?.DemandNum = value;
            data?.MinNum = value;
            SubsidiaryNumSetState?.call(() {}); //原片辅助数量(面积)
          }, onController: (controller) {
            _controller = controller;
          },
              mtextSelection: getTextSelection(_key),
              focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                (value) {
                  if (value) {
                    //聚焦
                    setTextSelection(_key, _controller?.selection); //记录焦点位置
                  } else {
                    //失去焦点
                    setTextSelection(_key, null);
                  }
                },
              ));
          return _edit;
        },
      );
      rowChildren.add(NumberOfApplications2);
      if (firstData.isSubsidiaryNum()) {
        //面积
        var StockArea = StatefulBuilder(
          builder: (contxet, setState) {
            SubsidiaryNumSetState = setState;
            return _text(data?.SubsidiaryNum2());
          },
        );
        rowChildren.add(StockArea);
      }
      if (firstData.CanWrite) {
        //品牌;(即可以选择系统里的品牌；又可以手动输入系统不存在的品牌)
        // var ManufacturerName2 = data?.ManufacturerName;
        // if (StringUtils.isEmpty(ManufacturerName2)) {
        //   ManufacturerName2 = AppStrings.of(context).ManufacturerName2;
        // }
        var ManufacturerName2 = AppStrings.of(context).ManufacturerName2;
        var ManufacturerName =
            _materialButton(ManufacturerName2 ?? "", onPressed: () {
          // _setState?.call(() {
          //   //fixme 获取品牌，需要接口对接
          // });
          PreSearchMaterialInfo searchData = PreSearchMaterialInfo();
          searchData.type = PreSearchMaterialInfo.Type_ManufacturerName;
          searchData.MaterialType = data?.MaterialType;
          searchData.MaterialTypeId = data?.MaterialTypeId ?? "";
          AppRouteHelper.goSearchProjiectNameRoute(context, searchData,
              (value) {
            _setState?.call(() {
              //fixme 需要对接接口
              if (value is OtherWorkApply) {
                data?.ManufacturerName = value.Name;
                data?.ManufacturerId = value.Id;
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              }
            });
          });
        });

        //手写品牌
        var CanManufacturerName = StatefulBuilder(
          builder: (contxet, setState) {
            return UiBase.itemWithSigleEdit(context, data?.ManufacturerName,
                isAllowEmpty: true, isLine: true, onChanged: (value) {
              data?.ManufacturerName = value;
              data?.ManufacturerId = "0"; //手输id不要为空，防止出错。
              getStockNum(context, CurrentInventorySetState,
                  MaterialCodeSetState, data);

              ///库存数量
            });
          },
        );
        // rowChildren.add(Container(child: CanManufacturerName,width: 200,));
        rowChildren.add(Container(
          child: Row(
            children: [
              Container(
                child: CanManufacturerName,
                width: 150,
              ),
              Container(
                child: ManufacturerName,
                width: 150,
              )
            ],
          ),
          width: 300,
        ));
      } else {
        //品牌
        // var ManufacturerName = _text(data?.ManufacturerName);
        // rowChildren.add(ManufacturerName);
        var ManufacturerName2 = data?.ManufacturerName;
        if (StringUtils.isEmpty(ManufacturerName2)) {
          ManufacturerName2 = AppStrings.of(context).ManufacturerName2;
        }
        var ManufacturerName =
            _materialButton(ManufacturerName2 ?? "", onPressed: () {
          // _setState?.call(() {
          //   //fixme 获取品牌，需要接口对接
          // });
          PreSearchMaterialInfo searchData = PreSearchMaterialInfo();
          searchData.type = PreSearchMaterialInfo.Type_ManufacturerName;
          searchData.MaterialType = data?.MaterialType;
          searchData.MaterialTypeId = data?.MaterialTypeId ?? "";
          AppRouteHelper.goSearchProjiectNameRoute(context, searchData,
              (value) {
            _setState?.call(() {
              //fixme 需要对接接口
              if (value is OtherWorkApply) {
                data?.ManufacturerName = value.Name;
                data?.ManufacturerId = value.Id;
                getStockNum(context, CurrentInventorySetState,
                    MaterialCodeSetState, data);

                ///库存数量
              }
            });
          });
        });
        rowChildren.add(ManufacturerName);
      }

      ///当前库存
      var CurrentInventory = StatefulBuilder(
        builder: (contxet, setState) {
          CurrentInventorySetState = setState;
          var CurrentInventory = _text(data?.StockNum2());
          return CurrentInventory;
        },
      );
      rowChildren.add(CurrentInventory);
      //备注
      if (isModifyBeizhu) {
        //可以填写
        var ListBeizhu = StatefulBuilder(
          builder: (contxet, setState) {
            return UiBase.itemWithSigleEdit(context, data?.ListBeizhu,
                isAllowEmpty: true, isLine: true, onChanged: (value) {
              data?.ListBeizhu = value;
            });
          },
        );
        rowChildren.add(ListBeizhu);
      } else {
        var ListBeizhu = _text("${data?.ListBeizhu}");
        rowChildren.add(ListBeizhu);
      }
      //操作
      if (isAdd) {
        if (i == 0) {
          var Operation = AppUi.getEmptyView();
          rowChildren.add(Operation);
        } else {
          var Operation =
              _materialButton(AppStrings.of(context).delete, onPressed: () {
            //删除
            _setState?.call(() {
              datas?.removeAt(i);
            });
          });
          rowChildren.add(Operation);
        }
      }
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: IntrinsicColumnWidth(),
        1: IntrinsicColumnWidth(),
        2: IntrinsicColumnWidth(),
        3: IntrinsicColumnWidth(),
        4: IntrinsicColumnWidth(),
        5: IntrinsicColumnWidth(),
        6: IntrinsicColumnWidth(),
        7: IntrinsicColumnWidth(),
        8: IntrinsicColumnWidth(),
        9: IntrinsicColumnWidth(),
        10: IntrinsicColumnWidth(),
        11: IntrinsicColumnWidth(),
        12: IntrinsicColumnWidth(),
        13: IntrinsicColumnWidth(),
        14: IntrinsicColumnWidth(),
        15: IntrinsicColumnWidth(),
        16: IntrinsicColumnWidth(),
        17: IntrinsicColumnWidth(),
        18: IntrinsicColumnWidth(),
        19: IntrinsicColumnWidth(),
      },
      children: children,
    );
    return table;
  }

  ///获取库存数量
  static getStockNum(
      BuildContext context,
      StateSetter? CurrentInventorySetState,
      StateSetter? MaterialCodeSetState,
      PurDemand data) {
    ///data?.StockNum
    ///fixme 获取库存数量
    MaterialModel.getStockNum(context, data, false, (value) {
      if (value.isSuccessForCode()) {
        CurrentInventorySetState?.call(() {
          data?.StockNum = value.StockNum;
          //print("物料请购库存：${data?.StockNum}");
        });
      }
    });

    ///fixme 获取物料编码
    getMaterialNumber(_SupplierId, context, MaterialCodeSetState, data);
  }

  ///fixme 获取物料编码
  static getMaterialNumber(String SupplierId, BuildContext context,
      StateSetter? MaterialCodeSetState, PurDemand data) {
    AjaxSalesModel?.getMaterialNumber(SupplierId, context, false, data: data,
        callback: (value) {
      MaterialCodeSetState?.call(() {
        data?.MaterialCode = value; //物料编码
      });
    });
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(String? text, {bool isStart = false}) {
    // return Center(
    //   child: Text(text ?? ""),
    // );
    Widget child;
    if (isStart) {
      var textKey = Text(
        text ?? "",
        style: AppStyle.textStyleWithCard(),
      );
      var value = "*";
      var startText = Text(
        value,
        softWrap: true,
        style: AppStyle.textStyleWithCardRed(),
      );
      child = SizedBox(
        child: Row(
          children: [textKey, startText],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        width: 120,
      );
    } else {
      child = Text(text ?? "");
    }
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: 36.0, //最小高度
        ),
        child: Center(
          child: child,
        ),
      ),
    );
  }

  //复选框
  //isChecked 是否选中
  //isEnable 是否可操作
  //onChanged 选中回调
  static Widget _checkbox(bool isChecked,
      {bool isEnable = true, Function(bool)? onChanged}) {
    Color activeColor = Colors.blueAccent;
    Color inactiveColor = Colors.black;
    if (!isEnable) {
      //不可用，颜色变暗。
      activeColor = Colors.black12;
      inactiveColor = Colors.black12;
    }
    return Container(
      alignment: Alignment.center,
      // height: 30,
      // width: 30,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      child: CircleCheckbox(
        isEnable: isEnable,
        value: isChecked,
        //value 是否选中
        width: 20,
        //width 宽度
        height: 20,
        //height 高度
        activeColor: activeColor,
        //activeColor 选中时背景颜色
        inactiveColor: inactiveColor,
        //inactiveColor 未选中时颜色
        style: CircleCheckboxStyle.tick_hollow,
        //circle_point 圆点样式
        //checked: , 自定义选中组件；fixme 优先级比以上属性设置要高。
        //unChecked: ,自定义未选中组件
        onChanged: (bool) {
          //选中状态改变时回调，如点击时。
          //选中状态改变时回调。
          //setState(() {});
          if (isEnable) {
            onChanged?.call(bool);
          }
        },
      ),
    );
  }

  ///按钮
  static Widget _materialButton(String text,
      {VoidCallback? onPressed,
      double radius = 5,
      double height = 35,
      double width = 50,
      Color color = Colors.blueAccent,
      Color textColor = Colors.white,
      double fontSize = 14,
      EdgeInsetsGeometry margin = const EdgeInsets.only(left: 8, right: 8),
      EdgeInsetsGeometry padding =
          const EdgeInsets.only(left: 16, right: 16)}) {
    return Container(
      margin: margin,
      child: MaterialButton(
        padding: padding,
        height: height,
        minWidth: width,
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: color,
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: fontSize,
          ),
        ), //fixme 子控件
      ),
    );
  }
}
